import React, { useState, useEffect } from'react';
import { provinceCityData } from '../../config/provinceCityData';
import CitySelector from './CitySelector';
import WeatherDetail from './WeatherDetail';
import { API_KEY, BASE_URL } from '../../config'

import './index.less'


// 定义天气数据结构
interface WeatherForecast {
    date: string;
    week: string;
    dayweather: string;
    nightweather: string;
    daytemp: string;
    nighttemp: string;
}

interface WeatherData {
    city: string;
    forecasts: WeatherForecast[];
}

// 星期转换函数
const getFullWeekday = (week: string): string => {
    const weekdayMap = {
        '1': '星期一',
        '2': '星期二',
        '3': '星期三',
        '4': '星期四',
        '5': '星期五',
        '6': '星期六',
        '7': '星期日'
    };
    return weekdayMap[week] || week;
};

const App: React.FC = () => {
    const [city, setCity] = useState<string>('310000');
    const [weatherData, setWeatherData] = useState<WeatherData | null>(null);
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [selectedForecast, setSelectedForecast] = useState<WeatherForecast | null>(null);

    const fetchWeatherData = async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await fetch(`${BASE_URL}?key=${API_KEY}&city=${city}&extensions=all&output=JSON`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            if (data.info === 'OK') {
                setWeatherData({
                    city: data.forecasts[0].city,
                    forecasts: data.forecasts[0].casts.slice(0, 7)
                });
                setSelectedForecast(data.forecasts[0].casts.slice(0, 1)[0]);
            } else {
                throw new Error(data.info);
            }
        } catch (err) {
            if (err instanceof Error) {
                setError(err.message);
            }
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchWeatherData();
    }, [city]);

    const handleCityChange = (selectedArea: string[]) => {
        setCity(selectedArea[selectedArea.length - 1]);
    };

    return (
        <div className="app">
            <CitySelector
                provinceCityData={provinceCityData}
                handleCityChange={handleCityChange}
            />
            {loading && <p>加载中...</p>}
            {error && <p className="error">{error}</p>}
            {weatherData && (
                <WeatherDetail
                    weatherData={weatherData}
                    selectedForecast={selectedForecast}
                    setSelectedForecast={setSelectedForecast}
                    getFullWeekday={getFullWeekday}
                />
            )}
        </div>
    );
};

export default App;
